<template>
  <view class="container">
    <view class="head">
      <view class="logo">
        <image src="/static/logo.png"></image>
      </view>
      <text>研汇教育</text> 
    </view>
    <!-- 非第一次登录 -->
    <view class="main" v-if="!state.isZhuce">
      <button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" class="loginBtn">登录</button>
      <input class="uni-input"  placeholder="邀请码" @blur="changeInvite"/>
      <button @click="noLogin" class="loginBtn" style="background-color: lightgray; color: #ffffff; margin-top: 14px;">暂不登录</button>
    </view>
    <!-- 第一次登录 -->
    <view class="formMain" v-if="state.isZhuce">
      <view class="formItem">
        <view class="label">名称</view>
        <view class="itemRight">
          <input class="itemInput" @blur="changeNickName"/>
        </view>
      </view>
      <view class="formItem">
        <view class="label">学历层次</view>
        <view class="itemRight">
          <picker @change="bindPickerChange" :value="state.index" :range="state.array">
            <view class="uni-input" v-if="state.array[state.index]">{{state.array[state.index]}}</view>
            <view class="uni-input placeholder" v-else>请选择学历层次</view>
          </picker>
        </view>
      </view>
      <view class="formItem">
        <view class="label">擅长软件</view>
        <view class="itemRight">
          <input class="itemInput" @blur="changePoint"/>
        </view>
      </view>
      <view class="zhuce" @click="clickBtn">注册</view>
    </view>
  </view>
</template>

<script setup>
  import { reactive, ref } from 'vue';
  import { loginWx, getLoginRole, registerTeacher,phoneLogin } from '@/utils/login.js'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { device } from '../../utils/contanst';
  const state = reactive({
    index: null,
    array: ['985硕士', '985博士', '211硕士', '211博士', '本科'],
    isZhuce: false,
    password: null,
    nickname: null,
    strongPoint: null,
    headImg : null,
    userToken: null,
    role: null
  })
  onLoad(() => {
    checkLoginStatus()
    console.log(61, device)
  })
  const checkLoginStatus = () => {
    const userToken = uni.getStorageSync('userToken');
    state.userToken = uni.getStorageSync('userToken')
    if (userToken) {
      loginRole()
    } else {
      console.log(69)
    }
  }
const onGetPhoneNumber = (e) => {
  var that = this
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    // 用户点击了允许授权
    const {
      encryptedData,
      iv,
      code
    } = e.detail;
    // 将 encryptedData 和 iv 发送到后端服务器
    sendPhoneNumberToServer(encryptedData, iv, code);
  } else {
    // 用户点击了拒绝授权
    uni.showToast({
      title: '用户拒绝授权',
      icon: 'none'
    });
  }
}
// 点击暂不登录
const noLogin = () => {
  uni.redirectTo({
    url: '/pages/student/index'
  });
}
const sendPhoneNumberToServer = async(encryptedData, iv, code) => {
  phoneLogin({
    code,
    password:state.password
  }).then((res) => {
    console.log(95, res)
    if(res?.code == 1){
      wx.setStorageSync('userToken', res?.result?.token);
      wx.setStorageSync('userInfo', res?.result?.user)
      loginRole()
    } else if (res?.code == 4) {
      state.isZhuce = true
      wx.setStorageSync('userToken', res?.result?.token);
      wx.setStorageSync('userInfo', res?.result?.user)
    }
  })
}
  // 获取登录角色
  const loginRole = () => {
    getLoginRole({}).then((res) => {
      if (res?.code == 1) {
        console.log(112, res?.result)
        state.role = res?.result
        uni.setStorageSync('userRole', res?.result)
        uni.setStorageSync('tabBarBottom', device.safeAreaInsets.bottom)
        if (res?.result == 1) {
          uni.redirectTo({
            url: '/pages/student/index'
          });
        } else if (res?.result == 2) {
          uni.redirectTo({
            url: '/pages/frontPage/index'
          });
        } else if (res?.result == 3) {
          uni.redirectTo({
            url: '/pages/admin/index'
          });
        } else if (res?.result == 4) {
          uni.redirectTo({
            url: '/pages/teacher/index'
          });
        }
      } else if (res.code == -1) {
        uni.redirectTo({
        	url: '/pages/login/index'
        });
      } 
    })
  }
  const onGetUserInfo = (e) => {
    if (e.detail.userInfo) {
      // 用户点击了“同意”授权按钮
      const userInfo = e.detail.userInfo;
      console.log('用户信息：', userInfo);
      // 将用户信息发送到后端进行验证或注册
      login(userInfo);
    } else {
      // 用户点击了“拒绝”授权按钮
      wx.showToast({
        title: '授权失败，请重新授权',
        icon: 'none'
      });
    }
  }
  
  const changeNickName = (e) => {
    state.nickname = e?.detail?.value
  }
  const bindPickerChange = (e) => {
    console.log(58, e)
    state.index = e?.detail?.value
  }
  const changePoint = (e) => {
    state.strongPoint = e?.detail?.value
  }
  // 点击注册
  const clickBtn = () => {
    let params = {
      nickname: state.nickname,
      edu: state.array[state.index],
      strong_point: state.strongPoint
    }
    registerTeacher(params).then((res) => {
      if (res?.code == 1) {
        uni.redirectTo({
          url: '/pages/teacher/index'
        });
      } 
    })
  }
  const changeInvite = (e) => {
    console.log(55, e)
    state.password = e?.detail?.value
  }
  // 点击登录页面
  const login = (userInfo) => {
    uni.login({
      "provider": "weixin",
      "onlyAuthorize": true, // 微信登录仅请求授权认证
      success: function(event){
        const { code } = event
        if (code) {
          loginWx({code, password: state.password, head_img: userInfo?.avatarUrl}).then(async(res) => {
            if(res?.code == 1){
              wx.setStorageSync('userToken', res?.result?.token);
              wx.setStorageSync('userInfo', res?.result?.user)
              await loginRole()
            } else if (res?.code == 4) {
              state.isZhuce = true
              wx.setStorageSync('userToken', res?.result?.token);
              wx.setStorageSync('userInfo', res?.result?.user)
            }
          })
        }
      },
    })
  }
</script>

<style lang="scss" scoped>
  .container{
    width: 750rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    .head{
      width: 100%;
      height:640rpx;
      border-radius: 0 0 72rpx 72rpx;
      background: radial-gradient(132.09% 132.09% at 50% 47%, rgba(27, 79, 215, 0.48) 0%, #184BC9 46.63%);
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      .logo{
        width:246rpx;
        height:246rpx;
        border-radius: 100%;
        background: rgba(27, 79, 215, 0.31);
        display: flex;
        justify-content: center;
        align-items: center;
        image{
          width: 112rpx;
          height: 128rpx;
        }
      }
      text{
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 32px;
        line-height: 100%;
        letter-spacing: 0px;
        text-align: center;
        margin-top:20rpx;
        color: rgba(255, 255, 255, 1);

      }
    }
    .main{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top:40rpx;
      flex-direction: column;
      .loginBtn{
        width: 648rpx;
        height: 112rpx;
        border-radius: 16rpx;
        border-width: 2rpx;
        background: rgba(92, 148, 215, 0.24);
        border: 2rpx solid rgba(236, 236, 236, 1);
        box-shadow: 0 40rpx 54rpx 0 rgba(154, 154, 154, 0.08);
        display: flex;
        justify-content: center;
        align-items: center;
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 16px;
        line-height: 100%;
        letter-spacing: 0px;
        color: #ffffff;
      }
      .uni-input{
        width: 648rpx;
        height:76rpx;
        border: 2rpx solid rgba(0, 0, 0, 1);
        text-align: center;
        margin-top:30rpx;
      }
    }
    .formMain{
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 20rpx;
      .formItem{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        width:678rpx;
        margin-top:40rpx;
        .label{
          width: 180rpx;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 20px;
          line-height: 100%;
          letter-spacing: 0px;
          text-align: center;
          color: rgba(175, 175, 175, 1);
        }
        .itemRight{
          width: 462rpx;
          height: 58rpx;
          border-radius: 4rpx;
          background: rgba(255, 255, 255, 1);
          .itemInput{
            width: 100%;
            height:58rpx;
            padding-left: 2%;
            display: flex;
            // justify-content: center;
            align-items: center;
          }
          .uni-input{
            width: 100%;
            height:58rpx;
            padding-left: 2%;
            display: flex;
            // justify-content: center;
            align-items: center;
          }
          .placeholder{
            color: rgba(175, 175, 175, 1);
          }
        }
      }
      .zhuce{
        width: 226rpx;
        height: 96rpx;
        border-radius: 16rpx;
        color:#ffffff;
        margin-top: 60rpx;
        background: rgba(11, 105, 218, 1);
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 48rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
</style>